package com.wkbb.basic.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.enums.FaceReportStoreEnum;
import com.wkbb.basic.enums.FaceReportTargetEnum;
import com.wkbb.basic.enums.FaceReportTransferreEnum;
import com.wkbb.basic.feign.WxMsgFeignService;
import com.wkbb.basic.mapper.UserFaceOrderMapper;
import com.wkbb.basic.mapper.UserFaceStoreMapper;
import com.wkbb.basic.model.UserFaceOrder;
import com.wkbb.basic.model.UserFaceStore;
import com.wkbb.basic.service.StudentService;
import com.wkbb.basic.service.UserFaceReportService;
import com.wkbb.basic.vo.FaceReportVo;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.UserInfoDto;
import com.wkbb.common.dto.wx.MiniProgramDto;
import com.wkbb.common.dto.wx.WechatMessageDto;
import com.wkbb.common.dto.wx.WxMpTemplateDto;
import com.wkbb.common.enums.MpMsgTemplateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lizhichao
 * @date 2019/11/11
 * @description
 */
@Service
@Slf4j
public class UserFaceReportServiceImpl extends BaseServiceImpl implements UserFaceReportService {

    @Autowired
    private UserFaceOrderMapper userFaceOrderMapper;

    @Autowired
    private UserFaceStoreMapper userFaceStoreMapper;

    @Autowired
    private WxMsgFeignService thirdFeignService;

    @Autowired
    private StudentService studentService;

    @Autowired
    public void setMapper(UserFaceOrderMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    public PageInfo<FaceReportVo> getHeadQuartFaceReportPageInfoList(Map<String,Object> params,Integer pageNo,Integer pageSize){

        if (pageNo == null || pageSize == null) {
            return null;
        }
        //分页
        Page<FaceReportVo> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<FaceReportVo> pageInfo = new PageInfo(userFaceStoreMapper.getHeadQuartFaceReportPageInfoList(params));
        pageInfo.setTotal(page.getTotal());
        return pageInfo;

    }

    @Override
    public PageInfo<FaceReportVo> getAgentFaceReportPageInfoList(Map<String,Object> params,Integer pageNo,Integer pageSize){

        if (pageNo == null || pageSize == null) {
            return null;
        }
        //分页
        Page<FaceReportVo> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<FaceReportVo> pageInfo = new PageInfo(userFaceStoreMapper.getAgentFaceReportPageInfoList(params));
        pageInfo.setTotal(page.getTotal());
        return pageInfo;

    }

    @Override
    public List<UserFaceOrder> getFaceOrderHistory(Map<String,Object> params){

        return userFaceOrderMapper.getFaceOrderHistory(params);
    }

    @Transactional
    @Override
    public void insert(UserFaceOrder userFaceOrder,Boolean isSuper){

        //入订单表
        userFaceOrderMapper.insert(userFaceOrder);
        //向目标对象入库存表
        UserFaceStore userFaceStore = new UserFaceStore();
        userFaceStore.setUserId(userFaceOrder.getUserId());
        userFaceStore.setIsDonate(FaceReportTransferreEnum.UNDONATE.getValue());
        userFaceStore.setAmount(userFaceOrder.getAmount());
        userFaceStore.setObjectId(userFaceOrder.getTargetId());
        userFaceStore.setObjectType(userFaceOrder.getTargetType());
        userFaceStore.setStoreType(FaceReportStoreEnum.IN.getValue());//入库
        userFaceStoreMapper.insert(userFaceStore);
        //有赠送 再次入库存
        if(userFaceOrder.getGiveAmount() > 0){
            UserFaceStore userFaceStoreGive = new UserFaceStore();
            BeanUtils.copyProperties(userFaceStore,userFaceStoreGive);
            userFaceStoreGive.setIsDonate(FaceReportTransferreEnum.DONATE.getValue());
            userFaceStoreGive.setAmount(userFaceOrder.getGiveAmount());
            userFaceStoreMapper.insert(userFaceStoreGive);
        }

        //如果下放者身份不是超管 ，则需要减自己的库存（出库）
        if(!isSuper){
            UserFaceStore userFaceStoreOut = new UserFaceStore();
            userFaceStoreOut.setUserId(userFaceOrder.getUserId());
            userFaceStoreOut.setAmount(userFaceOrder.getAmount() + userFaceOrder.getGiveAmount());
            userFaceStoreOut.setObjectId(userFaceOrder.getOrgId());
            userFaceStoreOut.setObjectType(FaceReportTargetEnum.ORGANIZATION.getValue());//学校，代理商
            userFaceStoreOut.setIsDonate(FaceReportTransferreEnum.UNDONATE.getValue());
            userFaceStoreOut.setStoreType(FaceReportStoreEnum.OUT.getValue());//出库
            userFaceStoreMapper.insert(userFaceStore);
        }

    }

    @Override
    public FaceReportVo getUserFaceStoreInfo (Map<String,Object> params){

        return userFaceStoreMapper.getUserFaceStoreInfo(params);
    }

    @Override
    @Transactional
    public void addUserFaceOrderForStudent(UserFaceOrder userFaceOrder) {
        //入订单表
        userFaceOrderMapper.insert(userFaceOrder);
        //发送通知
        try {
            this.sendFaceResultToFamily(userFaceOrder);
        } catch (Exception e) {
            log.error("addUserFaceOrderForStudent-sendFaceResultToFamily推送消息异常!", e);
        }

        //给学生增加库存记录
        UserFaceStore userFaceStoreStudent = new UserFaceStore();
        userFaceStoreStudent.setUserId(userFaceOrder.getUserId());
        userFaceStoreStudent.setAmount(1);
        userFaceStoreStudent.setObjectId(userFaceOrder.getTargetId());
        userFaceStoreStudent.setObjectType(FaceReportTargetEnum.STUDENT.getValue());//学生
        userFaceStoreStudent.setIsDonate(FaceReportTransferreEnum.UNDONATE.getValue());
        //如果是开通人脸 则学生入库，回收则学生出库
        userFaceStoreStudent.setStoreType(userFaceOrder.getOrderType() == 1 ? FaceReportStoreEnum.IN.getValue() : FaceReportStoreEnum.OUT.getValue());
        userFaceStoreMapper.insert(userFaceStoreStudent);

        //给学校增加库存记录
        UserFaceStore userFaceStoreSchool = new UserFaceStore();
        userFaceStoreSchool.setAmount(1);
        userFaceStoreSchool.setObjectId(userFaceOrder.getOrgId());
        userFaceStoreSchool.setObjectType(FaceReportTargetEnum.ORGANIZATION.getValue());//学校
        userFaceStoreSchool.setIsDonate(FaceReportTransferreEnum.UNDONATE.getValue());
        //如果是开通人脸 则学校出库，回收则学校入库
        userFaceStoreSchool.setStoreType(userFaceOrder.getOrderType() == 1 ? FaceReportStoreEnum.OUT.getValue() : FaceReportStoreEnum.IN.getValue());
        userFaceStoreMapper.insert(userFaceStoreSchool);

    }

    @Override
    @Transactional
    public void addUserFaceOrderBatch(List<UserFaceOrder> userFaceOrders){

        userFaceOrderMapper.insertBatch(userFaceOrders);
    }

    /**
     * 推送开通人脸结果给家长
     *
     * @param userFaceOrder
     */
    private void sendFaceResultToFamily(UserFaceOrder userFaceOrder) throws Exception{

        //获取家长
        List<UserInfoDto> userInfoDtos = studentService.getGuardianInfoList(userFaceOrder.getTargetId());

        List<Long> toUserIdList = new ArrayList<>();
        for (UserInfoDto userInfoDto : userInfoDtos) {
            toUserIdList.add(userInfoDto.getId());
        }
        String first = userFaceOrder.getUserName() + "开通人脸成功";//todo
        this.sendFaceResult(userFaceOrder.getOrgId(),userFaceOrder.getTargetId(), first, new SimpleDateFormat("yyyy-MM-dd").format(new Date()),
                "", userInfoDtos.get(0).getOrgName(), toUserIdList);
    }

    /**
     * 开通，回收人脸推送
     * @param orgId 学校ID
     * @param first 标题
     * @param keyword1 时间
     * @param keyword2 晨检结果
     * @param remark 备注
     * @param toUserIdList 发送用户列表
     */
    private void sendFaceResult(Long orgId, Long userId,String first, String keyword1, String keyword2,
                             String remark, List<Long> toUserIdList){
        log.info("开通，回收人脸推送[sendFaceResult()]");
        try {
            WechatMessageDto wechatMessageDto = new WechatMessageDto();
            wechatMessageDto.setTemplateShortId(MpMsgTemplateEnum.MC_RESULT.getValue());

            List<WxMpTemplateDto> data = new ArrayList<>();
            WxMpTemplateDto firstMp = new WxMpTemplateDto();
            firstMp.setName("first");
            firstMp.setValue(first);
            firstMp.setColor("#07c062");
            data.add(firstMp);

            WxMpTemplateDto keyword1Mp = new WxMpTemplateDto();
            keyword1Mp.setName("keyword1");
            keyword1Mp.setValue(keyword1);
            data.add(keyword1Mp);

            WxMpTemplateDto keyword2Mp = new WxMpTemplateDto();
            keyword2Mp.setName("keyword2");
            keyword2Mp.setValue(keyword2);
            data.add(keyword2Mp);

            //备注
            WxMpTemplateDto remarkMp = new WxMpTemplateDto();
            remarkMp.setName("remark");
            remarkMp.setColor("#07c062");
            remarkMp.setValue(remark);
            data.add(remarkMp);

            //链接地址
//            MiniProgramDto miniProgramDto = new MiniProgramDto();
//            miniProgramDto.setUseSkip(false);
//            miniProgramDto.setPagePath("pages/attendanceCheckIn/parent/Parent?orgId=" + orgId +"&userId=" + userId+ "&goodsId=3");
//
//            wechatMessageDto.setMiniProgram(miniProgramDto);
            wechatMessageDto.setData(data);
            wechatMessageDto.setToUserList(toUserIdList);

            ResultDTO<Object> resultDTO = thirdFeignService.sendWxMsg(orgId, wechatMessageDto);

            if (resultDTO != null && resultDTO.isSuccess()) {
                log.info("Send message is successfully.");
            } else {
                log.error("Send message is failed.");
            }
        } catch (Exception e) {
            log.error("开通，回收人脸推送异常", e);
        }
    }

}